from django.http import JsonResponse

# 定义一个装饰器，验证是否已经登录
from django.conf import settings
import ihome.settings
from qiniu import Auth, put_file, etag
import qiniu.config
import datetime

import os
os.environ.setdefault(
    'DJANGO_SETTINGS_MODULE',
    'ihome.settings'
)

# 判断登录
def login_required(func):
    # func：是视图函数
    def wrapper(request, *args, **kwargs):
        # 添加功能代码
        if request.user.is_authenticated:
            return func(request, *args, **kwargs)
        else:
            return JsonResponse({'errno': 4101, 'errmsg': '未登录'})

    return wrapper



# 七牛云上传
def QiniuUpload(id, file_url):

    # 构建鉴权对象
    q = Auth(settings.QINIU_ACCESS_KEY, settings.QINIU_SECRET_KEY)

    # 需要上传的空间
    bucket_name = 'ihome-projects'

    time_str = datetime.datetime.now().strftime("%Y%m%d%H%M%S")  # 2019-07-06

    # 上传后保存的文件名
    key = id + time_str

    # 生成上传 Token， 可以指定过期时间等  q.upload_token(空间名, 文件名, 过期时间单位秒)
    # token = q.upload_token(bucket_name, key, 3600)
    token = q.upload_token(bucket_name, key)

    # 要上传文件的本地路径
    localfile = file_url

    ret, info = put_file(token, key, localfile)
    # print(info)
    assert ret['key'] == key
    assert ret['hash'] == etag(localfile)
    # print(ret['hash'])

    return key


# 上传文件测试
if __name__ == '__main__':

    result = QiniuUpload('1', '/home/ubuntu/Desktop/180702398.jpg')
    print(result)